//
//  HDGlobalFilterView.m
//  HDUIKit
//
//  Created by HaoDong chen on 2019/5/24.
//  Copyright © 2019 dong rights reserved.
//

#import "HDGlobalFilterView.h"
#import <objc/runtime.h>
#import "HDBaseDefine.h"
#import <Masonry/Masonry.h>

@interface HDGlobalFilterViewCell()<UIGestureRecognizerDelegate>
@end

@implementation HDGlobalFilterViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selfClick)];
        tap.delegate = self;
        [self.contentView addGestureRecognizer:tap];
    }
    return self;
}

- (void)selfClick {
    self.callback(self.hdModel);
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIControl class]]) {
        UIControl *cView = (UIControl *)touch.view;
        if (cView.allTargets.count) {
            return NO;
        }
    }
    return YES;
}
@end

@interface HDGlobalFilterView()<UIGestureRecognizerDelegate>
@property (nonatomic, strong) UIView *listBg;
@property (nonatomic, strong) HDCollectionView *listView;
@property (nonatomic, assign) CGFloat bottomMinGap;
@property (nonatomic, assign) CGFloat topMinGap;
@property (nonatomic, copy) void(^selectCallBack)(HDCellModel*);
@property (nonatomic, copy) void(^innerHideCallb)(void);
@property (nonatomic, assign) CGSize properSize;
@property (nonatomic, assign) CGFloat animationDuration;
@property (nonatomic, assign) BOOL isUpFilter;
@property (nonatomic, assign) CGFloat cornerR;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIColor *topBgColor;
@property (nonatomic, strong) UIColor *bottomBgColor;

@property (nonatomic, strong) UIColor *listViewBgColor;
@property (nonatomic, assign) CGFloat listViewCorR;
@property (nonatomic, strong) UIColor *listViewBorderC;
@property (nonatomic, assign) BOOL tapBgAutoHide;
@property (nonatomic, assign) BOOL tapCellAutoHide;
@property (nonatomic, assign) CGSize initailSize;
@end

@implementation HDGlobalFilterView
@synthesize isShow = _isShow;

- (BOOL)isNeedAutoFitHeight {
    return self.initailSize.height == 0;
}

- (void)setIsNeedTapBgAutoHide:(BOOL)tapBgAutoHide {
    self.tapBgAutoHide = tapBgAutoHide;
}

- (void)setIsNeedTapCellAutoHide:(BOOL)tapCellAutoHide {
    self.tapCellAutoHide = tapCellAutoHide;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    self.showInView = [UIApplication sharedApplication].keyWindow;
    [self setTapBgAutoHide:YES];
    [self setTapCellAutoHide:YES];
    return self;
}

- (void)orientationDidChange:(NSNotification*)noti {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self refreshView];
    });
}

- (HDCollectionView *)hdCollectionV
{
    return self.listView;
}

- (void)showWithSecArr:(NSMutableArray<HDSectionModel *> *)secArr referenceView:(UIView *)refView offset:(CGPoint)offset size:(CGSize)size bottomMinGap:(CGFloat)bottomMinGap animationDuration:(CGFloat)duration {
    [self showWithSecArr:secArr referenceView:refView offset:offset size:size bottomMinGap:bottomMinGap animationDuration:duration bottomCornerR:0];
}

- (void)showWithSecArr:(NSMutableArray<HDSectionModel *> *)secArr referenceView:(UIView *)refView offset:(CGPoint)offset size:(CGSize)size bottomMinGap:(CGFloat)bottomMinGap animationDuration:(CGFloat)duration bottomCornerR:(CGFloat)bottomCornerR {
    UIView *bgWindow = [self showInView];
    self.initailSize = size;
    self.cornerR = bottomCornerR;

    [self resetSubViews];
        
    CGRect orgRect         = [refView.superview convertRect:refView.frame toView:bgWindow];
    CGRect filterRect      = CGRectMake(orgRect.origin.x+offset.x, CGRectGetMaxY(orgRect)+offset.y, size.width, size.height);
    self.listBg.frame      = filterRect;
    CGRect frame           = self.listBg.frame;
    frame.size = size;
    self.listBg.frame = frame;
    self.listView.frame    = self.listBg.bounds;
    self.bottomMinGap      = bottomMinGap;
    self.animationDuration = duration;
    self.isUpFilter = NO;
    
    typeof(self) weakSelf = self;
    [self.listView hd_setAllDataArr:secArr];
    
    if ([self isNeedAutoFitHeight]) {
        [self.listView hd_setContentSizeChangeCallBack:^(CGSize newContentSize) {
            weakSelf.properSize = newContentSize;
            [weakSelf reSetWithNewContentSize:newContentSize];
            [weakSelf setCornersWithSize:newContentSize];
        }];
        if (!CGSizeEqualToSize(CGSizeZero, self.properSize)) {
            [self reSetWithNewContentSize:self.properSize];
            [self setCornersWithSize:self.properSize];
        }
    }else{
        [self reSetWithNewContentSize:size];
        [self setCornersWithSize:size];
    }
    [bgWindow addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    _isShow = YES;
}

- (void)showWithSecArr:(NSMutableArray<HDSectionModel *> *)secArr size:(CGSize)size topMinGap:(CGFloat)topMinGap topCornerRadius:(CGFloat)cornerR animationDuration:(CGFloat)duration {
    self.initailSize = size;
    UIView *bgWindow = [self showInView];
    [self resetSubViews];
    self.listBg.frame      = (CGRect){0,bgWindow.frame.size.height,size};
    self.listView.frame    = self.listBg.bounds;
    self.topMinGap      = topMinGap;
    self.animationDuration = duration;
    self.isUpFilter = YES;
    self.listView.collectionV.contentInset = UIEdgeInsetsMake(0, 0, HDSafeBottomHeight, 0);
    HDWeakSelf
    [self.listView hd_setAllDataArr:secArr];
    
    if ([self isNeedAutoFitHeight]) {
        [self.listView hd_setContentSizeChangeCallBack:^(CGSize newContentSize) {
            weakSelf.properSize = newContentSize;
            [weakSelf reSetWithNewContentSize:newContentSize];
            [weakSelf setCornersWithSize:newContentSize];
        }];
    }else{
        [self reSetWithNewContentSize:size];
        [self setCornersWithSize:size];
    }
    
    [bgWindow addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    _isShow = YES;
    self.cornerR = cornerR;
}

- (void)setSelectCallback:(void (^)(__kindof HDCellModel * _Nonnull))callback {
    self.selectCallBack = callback;
}

- (void)setInnerHideCallback:(void (^)(void))innerHideCb {
    self.innerHideCallb = innerHideCb;
}

- (void)hide:(BOOL)animated {
    self.topView.backgroundColor = self.topBgColor;
    self.bottomView.backgroundColor = self.bottomBgColor;
    if (animated) {
        [UIView animateWithDuration:self.animationDuration animations:^{
            if (self.isUpFilter) {
                CGRect frame = self.listBg.frame;
                frame.origin.y = self.showInView.frame.size.height;
                self.listBg.frame = frame;
            }else{
                CGRect frame = self.listBg.frame;
                frame.size.height = 0;
                self.listBg.frame = frame;
            }
            self.topView.backgroundColor = [UIColor clearColor];
            self.bottomView.backgroundColor = [UIColor clearColor];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }else{
        [self removeFromSuperview];
    }
    _isShow = NO;
    if (self.innerHideCallb) {
        self.innerHideCallb();
    }
}


- (void)resetSubViews {
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    self.listBg = [UIView new];
    self.listBg.clipsToBounds = YES;
//    LayerMakeCB(self.listBg, 0, 0.5, UIColorFromRGB(0xE7E8E9).CGColor);
    [self addSubview:self.listBg];
    
    self.listView = [HDCollectionView hd_makeHDCollectionView:^(HDCollectionViewMaker *maker) {
        maker.hd_isNeedTopStop(YES)
            .hd_isNeedAdaptScreenRotaion(YES);
    }];
    self.listView.collectionV.bounces = NO;
    self.listView.clipsToBounds = YES;
    [self.listBg addSubview:self.listView];
    
    if (@available(iOS 11.0, *)) {
        self.listView.collectionV.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self insertSubview:self.topView atIndex:0];
    [self insertSubview:self.bottomView atIndex:0];
    
    HDWeakSelf
    [self.listView hd_setAllEventCallBack:^(id backModel, HDCallBackType type) {
        [weakSelf cellClickCallback:backModel];
    }];
    //    self.clipsToBounds = YES;
    self.properSize = CGSizeZero;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToHide)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tapHelper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHelper)];
    tapHelper.delegate = self;
    [self.listBg addGestureRecognizer:tapHelper];
}

- (void)tapToHide {
    if (self.tapBgAutoHide) {
        [self hide:YES];
    }
}

- (void)tapHelper {
    
}

- (void)cellClickCallback:(id)model {
    if (self.selectCallBack) {
        self.selectCallBack(model);
    }
    if (self.tapCellAutoHide) {
        [self hide:YES];
    }
}

- (void)reSetWithNewContentSize:(CGSize)contentSize {
    CGFloat fitH = self.listBg.frame.size.height;
    CGFloat maxH = 0;
    BOOL isNeedReCalculateSize = ABS(fitH - contentSize.height) > 1;
    if ([self isNeedAutoFitHeight] && fitH > self.showInView.frame.size.height) {
        isNeedReCalculateSize = YES;
    }
    if (isNeedReCalculateSize) {
        if (self.isUpFilter) {
            maxH = self.showInView.frame.size.height - HDSafeTopHeight - _topMinGap;
            if (contentSize.height+HDSafeBottomHeight<maxH) {
                fitH = contentSize.height+HDSafeBottomHeight;
                self.listView.collectionV.contentInset = UIEdgeInsetsZero;
            }else{
                fitH = maxH;
                self.listView.collectionV.contentInset = UIEdgeInsetsMake(0, 0, HDSafeBottomHeight, 0);
            }
            
        }else{
            maxH = self.showInView.frame.size.height - HDSafeBottomHeight - _bottomMinGap - CGRectGetMinY(self.listBg.frame);
            fitH = MIN(contentSize.height, maxH);
        }
    }
    
    fitH = floor(fitH);
    if (self.isUpFilter) {
        [UIView animateWithDuration:self.animationDuration animations:^{
            CGRect frame = self.listBg.frame;
            frame.origin.y = self.showInView.frame.size.height - fitH;
            self.listBg.frame = frame;
            self.topView.backgroundColor = self.topBgColor;
            self.bottomView.backgroundColor = self.bottomBgColor;
        }];
        CGRect frame = self.listBg.frame;
        frame.size.height = fitH;
        self.listBg.frame = frame;
    }else{
        [UIView animateWithDuration:self.animationDuration animations:^{
            CGRect frame = self.listBg.frame;
            frame.size.height = fitH;
            self.listBg.frame = frame;
            self.topView.backgroundColor = self.topBgColor;
            self.bottomView.backgroundColor = self.bottomBgColor;
        }];
    }
    CGRect frame = self.listView.frame;
    frame.size.height = fitH;
    self.listView.frame = frame;
    self.listView.collectionV.frame = self.listView.bounds;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIControl class]]) {
        UIControl *cView = (UIControl *)touch.view;
        if (cView.allTargets.count) {
            return NO;
        }
    }
    //默认都需要响应
    return YES;
}

- (void)setCornersWithSize:(CGSize)properSize {
    if (self.cornerR>0) {
        UIBezierPath *maskPath;
        if (self.isUpFilter) {
            maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, properSize.width, properSize.height) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(self.cornerR,self.cornerR)];
        }else{
            maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, properSize.width, properSize.height) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(self.cornerR,self.cornerR)];
        }
        static char *maskLayerKey;
        CAShapeLayer *maskLayer = objc_getAssociatedObject(self, &maskLayerKey);
        if (!maskLayer) {
            maskLayer = [[CAShapeLayer alloc] init];
            objc_setAssociatedObject(self, &maskLayerKey, maskLayer, OBJC_ASSOCIATION_RETAIN);
        }
        maskLayer.frame = CGRectMake(0, 0, properSize.width, properSize.height);
        maskLayer.path = maskPath.CGPath;
        self.listBg.layer.mask = maskLayer;
    }
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [UIView new];
        _topView.backgroundColor = [UIColor clearColor];
    }
    return _topView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = [UIColor clearColor];
    }
    return _bottomView;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self refreshView];
}

- (void)refreshView {
    CGRect frame = self.listBg.frame;
    frame.size.width = self.showInView.frame.size.width;
    self.listBg.frame = frame;
    self.listView.frame = self.listBg.bounds;
    
    [self.listView hd_reloadAll];

    self.topView.frame = CGRectMake(0, 0, self.showInView.frame.size.width, _listBg.center.y);
    self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.topView.frame), self.showInView.frame.size.width, self.frame.size.height - CGRectGetMaxY(self.topView.frame));
    
    if (self.listViewBgColor) {
        self.listView.backgroundColor = self.listViewBgColor;
    }
    if (self.listViewBorderC) {
        self.listView.layer.cornerRadius = self.listViewCorR;
        self.listView.layer.masksToBounds = YES;
        self.listView.layer.borderWidth = 0.5;
        self.listView.layer.borderColor = self.listViewBorderC.CGColor;
    }
}

- (void)setTopBgColor:(UIColor *)topBgColor bottomBgColor:(UIColor *)bottomBgColor {
    self.topBgColor = topBgColor;
    self.bottomBgColor = bottomBgColor;
}

- (void)setListViewBgColor:(UIColor *)bgColor cornerR:(CGFloat)corR borderColor:(UIColor *)borderC {
    self.listViewCorR = corR;
    self.listViewBgColor = bgColor;
    self.listViewBorderC = borderC;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


